package MicroRpc.framework.protocol.dubbo.json;

import MicroRpc.framework.beans.Invoker;
import MicroRpc.framework.beans.Url;
import MicroRpc.framework.excption.CommException;
import MicroRpc.framework.loadbalance.LoadBalance;
import MicroRpc.framework.protocol.handler.AbstractProtocolHandler;
import MicroRpc.framework.redis.Registry.core.RedisRegistry;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
//json版本
@Slf4j(topic = "m.DubboProtocol")
public class DubboProtocol extends AbstractProtocolHandler {
    private final DubboClient dubboClient=new DubboClient();
    private final ObjectMapper objectMapper=new ObjectMapper();
    public final static String ERROR_MSG="目标url已断开连接,为你重新分配合适的服务:";
    public DubboProtocol(LoadBalance loadBalance) {
        super(loadBalance);
    }

    @Override
    public Object send(Invoker invoker) {
        Url url = loadBalance.selectUrl(invoker);
        if (url==null){
            log.error("当前服务提供者列表没有对应的服务.");
            return null;
        }
        try {
            Object result = dubboClient.send(url, invoker);
            return objectMapper.readValue(result.toString(),Object.class);
        } catch (CommException | InterruptedException   | IOException e) {
            RedisRegistry.adviceFail(url);
            log.error("invoker发送时异常,目标url: {}",url.getHost()+":"+url.getPort());
        }
        return null;
    }

    @Override
    public void recv(Url url) {
        NettyServer.serverStart(url);
    }

}
